<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="JinYan&#39;s blog">
  <meta name="keyword" content="hexo-theme, vuejs">
  
    <link rel="shortcut icon" href="/blog/css/images/logo.jpg">
  
  <title>
    
      Python-3-字符串 | SanYuanEmpire
    
  </title>
  <link href="//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdn.bootcss.com/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdn.bootcss.com/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  <link rel="stylesheet" href="/blog/css/style.css">
<link rel="stylesheet" href="/blog/css/plugins/gitment.css">
  <script src="//cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdn.bootcss.com/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdn.bootcss.com/nprogress/0.2.0/nprogress.min.js"></script>
  <script src="/blog/js/qrious.js"></script>
<script src="/blog/js/gitment.js"></script>
  
  
    <!-- MathJax support START -->
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
    <!-- MathJax support END -->
  


</head>
<div class="wechat-share">
  <img src="/css/images/logo.jpg" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/blog/">
      <div class="logo"></div>
      <span>SanYuanEmpire</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/blog/" class="item-link">Home</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/blog/archives/" class="item-link">Archives</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/blog/" class="menu-link">Home</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/blog/archives/" class="menu-link">Archives</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>Python-3-字符串</h2>
  <p class="post-date">2018-08-30</p>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h1 id="字符串-string"><a href="#字符串-string" class="headerlink" title="字符串(string)"></a>字符串(string)</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">单引号和双引号使用完全相同</span><br><span class="line">使用三引号(&apos;&apos;&apos;或&quot;&quot;&quot;)可以指定一个多行字符串</span><br><span class="line">转义符(反斜杠\)可以用来转义，使用r可以让反斜杠不发生转义，如r&quot;this is a line with \n&quot;，则\n会显示，并不是换行</span><br><span class="line">按字面意义级联字符串，如&quot;this &quot; &quot;is &quot; &quot;string&quot;会被自动转换为this is string</span><br><span class="line">字符串可以用 + 运算符连接在一起，用 * 运算符重复</span><br><span class="line">字符串有两种索引方式，从左往右以 0 开始，从右往左以 -1 开始</span><br><span class="line">字符串不能改变</span><br><span class="line">没有单独的字符类型，一个字符就是长度为 1 的字符串</span><br><span class="line">字符串的截取的语法格式如下：变量[头下标:尾下标]</span><br></pre></td></tr></table></figure>
<hr>
<h1 id="转义字符"><a href="#转义字符" class="headerlink" title="转义字符"></a>转义字符</h1><p><img src="http://wx2.sinaimg.cn/mw690/705e8c43gy1furr3x2nfgj20cj0ewt94.jpg" alt="转义字符"></p>
<hr>
<h1 id="字符串运算符"><a href="#字符串运算符" class="headerlink" title="字符串运算符"></a>字符串运算符</h1><p><img src="http://wx1.sinaimg.cn/mw690/705e8c43gy1furr440qssj20jq0fuwly.jpg" alt="字符串运算符"></p>
<hr>
<h1 id="字符串格式化"><a href="#字符串格式化" class="headerlink" title="字符串格式化"></a>字符串格式化</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">在 Python 中，字符串格式化不是 sprintf 函数，而是用 % 符号。例如：</span><br><span class="line"></span><br><span class="line">print(<span class="string">"我叫%s， 今年 %d 岁！"</span> % (<span class="string">'小明'</span>, <span class="number">10</span>))</span><br><span class="line"></span><br><span class="line">// 输出:</span><br><span class="line"></span><br><span class="line">我叫小明， 今年 <span class="number">10</span> 岁！</span><br></pre></td></tr></table></figure>
<hr>
<h1 id="格式化符号"><a href="#格式化符号" class="headerlink" title="格式化符号"></a>格式化符号</h1><p><img src="http://wx2.sinaimg.cn/mw690/705e8c43gy1furr59a0yvj20an0c9t8o.jpg" alt="格式化符号"></p>
<hr>
<h1 id="辅助指令"><a href="#辅助指令" class="headerlink" title="辅助指令"></a>辅助指令</h1><p><img src="http://wx4.sinaimg.cn/mw690/705e8c43gy1furr4e705jj20i408w749.jpg" alt="辅助指令"></p>
<p>Python 2.6 开始，新增了一种格式化字符串的函数 str.format()，它增强了字符串格式化的功能。</p>
<hr>
<h1 id="多行字符串"><a href="#多行字符串" class="headerlink" title="多行字符串"></a>多行字符串</h1><blockquote>
<p>用三引号(‘’’ 或 “””)包裹字符串内容<br>多行字符串内容支持转义符，用法与单双引号一样<br>三引号包裹的内容，有变量接收或操作即字符串，否则就是多行注释<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">实例：</span><br><span class="line">string = <span class="string">'''</span></span><br><span class="line"><span class="string">print(\tmath.fabs(-10))</span></span><br><span class="line"><span class="string">print(\nrandom.choice(li))</span></span><br><span class="line"><span class="string">'''</span></span><br><span class="line">print(string)</span><br><span class="line">输出：</span><br><span class="line">print( math.fabs(<span class="number">-10</span>))</span><br><span class="line">print(</span><br><span class="line">random.choice(li))</span><br></pre></td></tr></table></figure></p>
</blockquote>
<hr>
<h1 id="Unicode"><a href="#Unicode" class="headerlink" title="Unicode"></a>Unicode</h1><p>在 2.x 中，普通字符串是以 8 位 ASCII 码进行存储的，而 Unicode 字符串则存储为 16 位 Unicode 字符串，这样能够表示更多的字符集。使用的语法是在字符串前面加上前缀 u。<br>在 3.x 中，所有的字符串都是 Unicode 字符串。</p>
<hr>
<h1 id="字符串函数"><a href="#字符串函数" class="headerlink" title="字符串函数"></a>字符串函数</h1><p><img src="http://wx3.sinaimg.cn/mw690/705e8c43gy1furr4nk2xoj20jw0djq9x.jpg" alt="字符串函数"></p>
<h1 id="字节-bytes"><a href="#字节-bytes" class="headerlink" title="字节(bytes)"></a>字节(bytes)</h1><blockquote>
<p>在 3.x 中，字符串和二进制数据完全区分开。文本总是 Unicode，由 str 类型表示，二进制数据则由 bytes 类型表示。Python 3 不会以任意隐式的方式混用 str 和 bytes，你不能拼接字符串和字节流，也无法在字节流里搜索字符串（反之亦然），也不能将字符串传入参数为字节流的函数（反之亦然）。<br>bytes 类型与 str 类型，二者的方法仅有 encode() 和 decode() 不同。<br>bytes 类型数据需在常规的 str 类型前加个 b 以示区分，例如 b’abc’。<br>只有在需要将 str 编码(encode)成 bytes 的时候，比如：通过网络传输数据；或者需要将 bytes 解码(decode)成 str 的时候，我们才会关注 str 和 bytes 的区别。</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">bytes 转 str：</span><br><span class="line"><span class="string">b'abc'</span>.decode()</span><br><span class="line">str(<span class="string">b'abc'</span>)</span><br><span class="line">str(<span class="string">b'abc'</span>, encoding=<span class="string">'utf-8'</span>)</span><br><span class="line">str 转 bytes：</span><br><span class="line"><span class="string">'中国'</span>.encode()</span><br><span class="line">bytes(<span class="string">'中国'</span>, encoding=<span class="string">'utf-8'</span>)</span><br></pre></td></tr></table></figure>
</section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/blog/2018/08/30/python-3-函数/">
        <span class="nav-arrow">← </span>
        
          python-3-函数
        
      </a>
    
    
      <a class="nav-right" href="/blog/2018/08/30/Python-3-列表/">
        
          Python-3-列表
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    
      <!-- No Comment -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
    <strong class="toc-title">Catalog</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#字符串-string"><span class="toc-nav-text">字符串(string)</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#转义字符"><span class="toc-nav-text">转义字符</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#字符串运算符"><span class="toc-nav-text">字符串运算符</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#字符串格式化"><span class="toc-nav-text">字符串格式化</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#格式化符号"><span class="toc-nav-text">格式化符号</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#辅助指令"><span class="toc-nav-text">辅助指令</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#多行字符串"><span class="toc-nav-text">多行字符串</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#Unicode"><span class="toc-nav-text">Unicode</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#字符串函数"><span class="toc-nav-text">字符串函数</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#字节-bytes"><span class="toc-nav-text">字节(bytes)</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'git@gitee.com:sanyuanempire/blog.git/2018/08/30/Python-3-字符串/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

     // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()
        
        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })

    // qrcode
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });

    // gitment
    var gitmentConfig = "";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "Python-3-字符串",
        owner: "",
        repo: "",
        oauth: {
          client_id: "",
          client_secret: ""
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  })();
</script>

<script>
  var disqus_shortname = '';
  
  var disqus_url = 'git@gitee.com:sanyuanempire/blog.git/2018/08/30/Python-3-字符串/';
  
  (function(){
    var dsq = document.createElement('script');
    dsq.type = 'text/javascript';
    dsq.async = true;
    dsq.src = '//go.disqus.com/embed.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
  })();
</script>

    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
  <p class="copyright">
    &copy; 2018 | Proudly powered by <a href="https://sanyuanempire.gitee.io/blog" target="_blank">JinYan</a>
    <br>
    Theme by <a href="https://sanyuanempire.gitee.io/blog">JinYan</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>
<!-- Baidu Tongji -->

<script src="/blog/js/script.js"></script>

  </body>
</html>